package com.wwy.provider;

import com.alibaba.fastjson.JSON;
import com.wwy.api.AbstractCacheService;
import com.wwy.util.JacksonUtil;
import net.sf.ehcache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Conditional;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Set;

@Service
public class RedisCacheService extends AbstractCacheService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public RedisCacheService(){}

    public void init(){
        super.init();
        System.out.println("eache init success!");
    }

    public boolean put(String key, Object value) {

        redisTemplate.opsForValue().set(key,JacksonUtil.toJson(value));

        System.out.println(key+"存入缓存成功！");
        return true;
    }

    public boolean put(String key, Object value, int seconds) {
        redisTemplate.opsForValue().set(key,JacksonUtil.toJson(value),seconds);
        System.out.println(key+"存入缓存成功！");
        return true;
    }

    public <T> T getCache(String key, Class<T> clz) {
        Object obj = this.redisTemplate.opsForValue().get(key);
        if (obj != null) {
            String jsonStr = String.valueOf(obj);
            return JacksonUtil.readValue(jsonStr, clz);
        } else {
            return null;
        }
    }

    public boolean delCache(String key) {
        try {
            this.redisTemplate.delete(key);
            // logger.info("删除缓存成功key为{}", this.combineKey(key));
            return true;
        } catch (Exception var3) {
            // logger.info("删除缓存失败key为{}", this.combineKey(key));
            var3.printStackTrace();
            return false;
        }
    }

    public <T> T keys(String keys, Class<T> clz) {
        Set<T> set = (Set<T>) this.redisTemplate.keys(keys);
        if (!set.isEmpty()) {
            String str = JSON.toJSONString(set);
            return JacksonUtil.readValue(str, clz);
        } else {
            return null;
        }
    }

    public boolean setNx(String key, Object value) {
        Boolean flag = this.redisTemplate.opsForValue().setIfAbsent(key, JacksonUtil.toJson(value));
        return flag;
    }

    public long increment(String key, long delta) {
        return this.redisTemplate.opsForValue().increment(key, delta);
    }

    public <T> T multiGet(Collection<String> keys, Class<T> clz) {
        List<T> list = (List<T>) this.redisTemplate.opsForValue().multiGet(keys);
        if (!list.isEmpty()) {
            String str = JSON.toJSONString(list);
            return JacksonUtil.readValue(str, clz);
        } else {
            return null;
        }
    }

}
